
import mode from "../../utils/mode.js"
const app = getApp()
var that
Page({

    /**
     * 页面的初始数据
     */
    data: {
        reportId:"",  //新报告Id
        showEnd:false,    //弹出提示
        question_age: '',    //答题年龄
        question_sex: '',    //答题性别
        list: [], //所有的问题
        answerIndex: 0,   //展示到第几题了
        nowId: 0,    //答到第几题了
        juli: "0",
        taikList: [],
        submitList: [],
        shunxu: 1, //排序
        twoMultiple: [],
        nowimg: '', //现在选中的图片
        nickName: '',
        openAnswer: '',
        overOne: false,
        userinfo: {},


        sortList: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    getdata () {     //获取题目列表
        var that = this
        mode.questionList().then(item => {
            let arr = item.data
            that.setData({
                list: arr
            })
            let nickName = that.data.userinfo.user_nickname
            nickName = nickName && nickName != undefined ? nickName : ''
            let sayHi = arr[0].name.replace(/【姓名】/, '  ' + nickName)
            arr[0].name = sayHi
            that.beStart(arr)
        })
    },
    beStart(arr){
        let that = this
        let talk = []
        setTimeout(() => {
            talk.push(arr[0])
            that.setData({
                taikList: talk,
                answerIndex: 1,
                nowId: 0,
            })
            that.toPush(arr,talk)
        }, 1500);
    },
    toPush(arr,talk){
        let that = this
        setTimeout(() => {
            talk.push(arr[1])
            that.setData({
                taikList: talk,
                answerIndex: 2,
                nowId: 1,
            })
        }, 1500);
    },
    async toAddCart (goods) {
        var that = this
        let addList = goods.split(',')
        let yijianList = []
        for (let index = 0; index < addList.length; index++) {
            const element = addList[index]
            let item = {
                goods_id: element,
                number: 1
            }
            yijianList.push(item)
        }
        that.setData({
            yijianList
        })

        //一键加购的商品
        let postData = JSON.stringify(yijianList)
        let { code, msg } = await mode.cartAdd({
            user_id: that.data.userinfo.id,
            goods_info: postData
        })
        if (code == 1) {
            console.log('加购成功');
        } else {
            wx.showToast({ title: msg, icon: 'none' })
        }
    },
    // 结束对话
    finishBtn () {
        app.backPage()
    },
    choiceIt (e) {   //点击选择   单项选择（单选  排序）
        var that = this
        let dataset = e.currentTarget.dataset   //
        let item = e.currentTarget.dataset.item     //当前题目
        let xuze = e.currentTarget.dataset.xz     //当前题目
        let choses = that.data.taikList[that.data.nowId].chose   //选择项数组
        let choseIndex = dataset.index    //选择项索引
        let nowShunxu = that.data.shunxu  //当前排序到多少
        let arr = that.data.list          //获取的所有题目列表
        let now_id = that.data.nowId      //当前答题索引
        // 肌肤排序
        if (now_id != item.sort_i - 1) return
        if (item.type == 4) {    //点击执行题目
            if (choseIndex == 1) {
                if (that.data.nowId > 1) {
                    let arr = []
                    let subArr = that.data.submitList
                    for (let index = 0; index < subArr.length; index++) {
                        const el = subArr[index]
                        if (el && el != null) {
                            arr.push(el)
                        }
                    }
                    if (that.data.userinfo.is_over_test == 1) {
                        wx.redirectTo({
                            url: '/pages/testReport/testRrport?testData=' + JSON.stringify(arr) + '&?isover=1',
                        })
                    } else {
                        wx.redirectTo({
                            url: '/pages/testReport/testRrport?testData=' + JSON.stringify(arr),
                        })
                    }
                } else {
                    let answer = choses[choseIndex]
                    that.data.taikList[now_id].user = []
                    that.data.taikList[now_id].user.push(answer)
                    //答题选择过性别和年龄   不展示对应题目
                    if (that.data.userinfo.question_age && that.data.userinfo.question_sex) {
                        arr[2].hideShow = true
                        arr[3].hideShow = true
                        that.data.taikList.push(arr[2])
                        if (that.data.userinfo.question_sex == '女生') {
                            arr[3].user = [{ answer_id: 1 }]
                            that.data.taikList.push(arr[3])
                            now_id = now_id + 2
                        } else {
                            arr[4].hideShow = true
                            that.data.taikList.push(arr[3])
                            that.data.taikList.push(arr[4])
                            now_id = now_id + 3
                        }
                        that.setData({
                            list: arr,
                            nowId: now_id
                        })
                    }
                    that.setData({
                        openAnswer: choses[choseIndex].key,
                        taikList: that.data.taikList,
                        sortList: []
                    })
                    that.nextStep()
                }
            } else {
                if (that.data.nowId > 1) {
                    wx.showLoading({
                        title: '保存报告数据',
                    })
                    let arr = []
                    let subArr = that.data.submitList
                    for (let index = 0; index < subArr.length; index++) {
                        const el = subArr[index]
                        if (el && el != null) {
                            arr.push(el)
                        }
                    }
                    mode.report(JSON.stringify(arr), that.data.userinfo.id).then(
                        item => {
                            if (item.code == 1) {
                                that.toAddCart(item.data.goods_info_ids)
                            } else {
                                wx.showToast({
                                    title: '保存报告失败',
                                    icon: 'error'
                                })
                            }
                        })
                } else {
                    that.finishBtn()  //返回
                }
            }
        } else if (dataset.item.type == 0) {// 单选
            if (item.is_sort == 1 && xuze.answer_id != 0 && dataset.item.p_id != 2) {
                that.data.sortList.push(xuze)
            }
            that.data.taikList[now_id].user = []
            that.data.taikList[now_id].user.push(dataset.xz)
            that.data.taikList[now_id].xz = dataset.xz.key
            that.data.submitList[item.sort_i - 1] = {
                'chose': choses[choseIndex].key,
                'id': item.id
            }
            that.setData({
                taikList: that.data.taikList,
                submitList: that.data.submitList,
                sortList: that.data.sortList,
            })
            that.nextStep()
        } else if (dataset.item.type == 1) { // 多选
            let id = dataset.id || 0     //点击chose内容选项的索引值
            let choseLen = dataset.item.chose.length - 1//   该题目的chose长度

            let nowChose = that.data.taikList[now_id].chose
            let items = nowChose[id]
            if (!items.isGrey) {
                console.log('tep1')
                if (!items.ischose) {
                    console.log('tep2')
                    that.data.taikList[now_id].chose[id].ischose = true
                    console.log('chose', id, choseLen)
                    if (id == choseLen) {
                        console.log('tep3')
                        that.setOtherGray(1)
                    } else {
                        if (that.data.taikList[now_id].no_use == 0) {
                            that.data.taikList[now_id].chose[choseLen].isGrey = true
                        }
                    }
                    that.data.twoMultiple.push(dataset.xz)
                } else {
                    console.log('tep5')
                    that.data.taikList[now_id].chose[id].ischose = false
                    that.data.twoMultiple.forEach((it, idx) => {
                        if (items.key == it.key) {
                            that.data.twoMultiple.splice(idx, 1)
                        }
                    })

                    if (id == choseLen) {
                        console.log('tep6')
                        that.setOtherGray(0)
                    } else {
                        console.log('tep7')
                        if (that.data.twoMultiple.length < 1 && that.data.taikList[now_id].no_use == 0) {
                            that.data.taikList[now_id].chose[choseLen].isGrey = false
                        }
                    }
                }
            }
            that.setData({
                twoMultiple: that.data.twoMultiple,
                taikList: that.data.taikList
            })
        } else if (dataset.item.type == 2) {  //排序
            choses.map((mapItem, index) => {
                if (index == choseIndex) {
                    if (!mapItem.sort_i) {    //选择项还未排序
                        that.data.taikList[now_id].chose[index].sort_i = nowShunxu
                        that.setData({
                            shunxu: nowShunxu + 1
                        })
                    } else {    //选择项已被排序
                        let choseSort = choses[choseIndex].sort_i
                        for (let i = 0; i < choses.length; i++) {
                            const it = choses[i]
                            if (it.sort_i > choseSort || it.sort_i == choseSort) {
                                it.sort_i = ''
                            }
                        }
                        that.data.taikList[that.data.nowId].chose = choses
                        that.setData({
                            shunxu: choseSort
                        })
                    }
                }
                return item
            })
            that.setData({
                taikList: that.data.taikList
            })

            if (that.data.shunxu > that.data.taikList[now_id].chose.length) {   //判断选项是否排序完毕
                that.setData({
                    overOne: true
                })
            } else {
                that.setData({
                    overOne: false
                })
            }
        }
        that.setStep()
        that.pageScrollToBottom()
    },
    setStep () {//同步进度条
        let oneStep = 100 / that.data.list.length
        that.setData({
            juli: (oneStep * Number(that.data.nowId)) + '%'
        })
    },
    setOtherGray (bloor) { // 设置其他的都是灰色
        console.log('置灰', bloor)
        let arr = this.data.taikList
        let nowId = that.data.nowId
        let arrItem = arr[nowId].chose
        if (arr[nowId].no_use == 0) {
            for (let index = 0; index < arrItem.length - 1; index++) {
                const element = arrItem[index]
                if (bloor == 1) {
                    element.isGrey = true
                } else {
                    element.isGrey = false
                }
            }
            this.data.taikList[nowId].chose = arrItem
            this.setData({
                taikList: this.data.taikList
            })
        }
    },
    // 多选选择完毕
    choiceOver (e) {
        let dataset = e.currentTarget.dataset
        let nowIndex = dataset.sj.sort_i    //当前题目sort
        let nowId = that.data.nowId
        if (dataset.sj.is_partake) {
            let sortArr = []
            dataset.sj.chose.sort(function (a, b) {
                return a.sort_i - b.sort_i
            })
            dataset.sj.chose.forEach(item => {
                sortArr.push(item.answer_id)
            })
            that.data.taikList[nowId].user = dataset.sj.chose
            that.data.submitList[that.data.nowId] = {
                'chose': sortArr.join(','),
                'id': dataset.sj.id
            }
            if (that.data.overOne) {   //已经排序完毕
                that.setData({
                    taikList: that.data.taikList,
                    submitList: that.data.submitList
                })
                that.nextStep()
            }
        } else if (dataset.sj.type == 1) {   //多选
            let a = []
            dataset.sj.chose.forEach(item => {
                if (item.ischose) {
                    a.push(item.key)
                    if (item.answer_id != 0 && dataset.sj.is_sort == 1) {
                        that.data.sortList.push(item)
                    }
                }
            })
            //处理多选     一项跳一题    多项走排序
            that.data.taikList[that.data.nowId].user = that.data.twoMultiple
            if (that.data.twoMultiple.length == 1) {
                let item = that.data.list[that.data.nowId]
                let nextItem = that.data.list[that.data.nowId + 1]
                that.data.submitList[that.data.nowId] = {
                    'chose': that.data.twoMultiple[0].key,
                    'id': that.data.list[that.data.nowId].id
                }
                let itemId = item.id + ''
                if (nextItem.p_id == itemId && nextItem.is_partake == 0) {    //下一题对上一题多选排序
                    console.log('zou')
                    nextItem.hideShow = true
                    that.data.submitList[that.data.nowId + 1] = {
                        'chose': that.data.twoMultiple[0].key,
                        'id': that.data.list[that.data.nowId + 1].id
                    }
                    console.log('nextItem', nextItem)
                    that.data.taikList.push(nextItem)
                    that.setData({
                        nowId: that.data.nowId + 1,
                        submitList: that.data.submitList,
                        taikList: that.data.taikList,
                        twoMultiple: []
                    })
                } else {
                    console.log('nozou')
                    that.setData({
                        submitList: that.data.submitList,
                        twoMultiple: []
                    })
                }
            } else {
                that.data.submitList[that.data.nowId] = {
                    'chose': a.join(','),
                    'id': that.data.taikList[that.data.nowId].id
                }
                that.setData({
                    taikList: that.data.taikList,
                    submitList: that.data.submitList,
                    sortList: that.data.sortList
                })
            }

            that.nextStep()
        } else {   //排序
            //处理
            let value = ''
            let sortArr = []
            dataset.sj.chose.sort(function (a, b) {
                return a.sort_i - b.sort_i
            })
            dataset.sj.chose.forEach(item => {
                value += (item.sort_i + '.' + item.value) + '\n'
                sortArr.push(item.key)
            })
            that.data.taikList[nowId].user = dataset.sj.chose
            that.data.submitList[that.data.nowId] = {
                'chose': sortArr.join(','),
                'id': dataset.sj.id
            }
            if (that.data.overOne) {   //已经排序完毕
                that.setData({
                    taikList: that.data.taikList,
                    submitList: that.data.submitList
                })
                that.nextStep()
            }
        }
        that.pageScrollToBottom()
    },
    tosetScore () {   //答题完毕     更新积分   跳转        
        var that = this
        let arr = []
        let subArr = that.data.submitList
        for (let index = 0; index < subArr.length; index++) {
            const el = subArr[index]
            if (el && el != null) {
                arr.push(el)
            }
        }

        // if (that.data.userinfo.is_over_test == 1) {     //第一次答题
            wx.redirectTo({
                url: '/pages/testReport/testRrport?id='+that.data.reportId
            })
        // } else {     //不是第一次答题
        //     wx.redirectTo({
        //         url: '/pages/testReport/testRrport?testData=' + JSON.stringify(arr),
        //     })
        // }
    },
    format (time, format) {     //日期格式
        var t = new Date(time)
        var tf = function (i) {
            return (i < 10 ? '0' : '') + i
        }
        return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
            switch (a) {
                case 'yyyy':
                    return tf(t.getFullYear())
                    break
                case 'MM':
                    return tf(t.getMonth() + 1)
                    break
                case 'mm':
                    return tf(t.getMinutes())
                    break
                case 'dd':
                    return tf(t.getDate())
                    break
                case 'HH':
                    return tf(t.getHours())
                    break
                case 'ss':
                    return tf(t.getSeconds())
                    break
            }
        })
    },
    // 下一题
    nextStep () {   //答完去下一题
        var that = this
        that.setData({
            nowId: that.data.nowId + 1,   //去下一题
            answerIndex: that.data.answerIndex + 1,
            overOne: false
        })
        if (that.data.nowId == that.data.list.length-1&&that.data.list[that.data.nowId].type==4){    // /  答完题目   有收尾
            that.data.taikList.push(that.data.list[that.data.nowId])
            setTimeout(() => {
                that.setData({
                    nowId: that.data.nowId,
                    taikList: that.data.taikList,
                    juli:'98%'
                })
                that.pageScrollToBottom()
                that.submitAnswer()
            }, 1500);
        }else if(that.data.nowId == that.data.list.length){
            //  答完题目   没有收尾题
                that.setData({
                    juli:'98%'
                })
                that.submitAnswer()
        } else {        //推题
            //把试题推送到展示列表
            let item = that.data.list[that.data.nowId]
            let lastItem = that.data.taikList[that.data.nowId - 1]
            if (item.p_id == 2) {
                if (that.data.userinfo.question_sex) {   //已答过性别
                    if (that.data.userinfo.question_sex == '女生') {
                        that.data.taikList.push(item)
                        setTimeout(() => {
                            that.setData({
                                nowId: that.data.nowId,
                                taikList: that.data.taikList
                            })
                        }, 1500);
                    } else {
                        item.hideShow = true
                        that.data.taikList.push(item)
                        that.data.taikList.push(that.data.list[that.data.nowId + 1])
                        that.data.nowId = that.data.nowId + 1
                        setTimeout(() => {
                            that.setData({
                                nowId: that.data.nowId,
                                taikList: that.data.taikList
                            })
                        }, 1500);
                    }
                } else {
                    if (lastItem.user[0].value == '女生') {
                        that.data.taikList.push(item)
                        setTimeout(() => {
                            that.setData({
                                nowId: that.data.nowId,
                                taikList: that.data.taikList
                            })
                        }, 1500);
                    } else {
                        item.hideShow = true
                        that.data.taikList.push(item)
                        that.data.taikList.push(that.data.list[that.data.nowId + 1])
                        that.data.nowId = that.data.nowId + 1
                        setTimeout(() => {
                            that.setData({
                                nowId: that.data.nowId,
                                taikList: that.data.taikList
                            })
                        }, 1500);
                    }
                }
            } else if (item.is_none == 1 && item.is_partake == 0) {  //存在前一题影响的
                let p_id = item.p_id.split(',')
                let arrLen = 0
                for (let mapI = 0; mapI < that.data.taikList.length; mapI++) {
                    const mapItem = that.data.taikList[mapI]
                    let inIndex = p_id.indexOf(mapItem.id + '')
                    if (inIndex > -1 && mapItem.user && mapItem.user[0].answer_id == 0) {
                        console.log('hjjjjj', inIndex)
                        arrLen = arrLen + 1
                    }
                }
                console.log('ppppp', p_id.length, arrLen)
                if (p_id.length == arrLen) {
                    item.hideShow = true
                    that.data.taikList.push(item)
                    that.data.taikList.push(that.data.list[that.data.nowId + 1])
                    that.data.nowId = that.data.nowId + 1
                } else {
                    that.data.taikList.push(item)
                }
                setTimeout(() => {
                    that.setData({
                        nowId: that.data.nowId,
                        taikList: that.data.taikList,
                        twoMultiple: [],
                        shunxu: 1,
                    })
                }, 1500);
            } else if (item.is_partake != 1) {
                if (item.type == 2) {   //推送多选
                    item.chose = that.data.twoMultiple
                }
                that.data.taikList.push(item)
                setTimeout(() => {
                    that.setData({
                        nowId: that.data.nowId,
                        taikList: that.data.taikList,
                        twoMultiple: [],
                        shunxu: 1,
                    })        
                }, 1500);
                
            } else {
                that.goBeAll()   //去判断排序所有选项
            }

            setTimeout(function () {
                that.pageScrollToBottom()
            }, 1800)
        }

    },
    submitAnswer(){//提交答案
        var that = this
        let arr = []
        let subArr = that.data.submitList
        for (let index = 0; index < subArr.length; index++) {
            const el = subArr[index]
            if (el && el != null) {
                arr.push(el)
            }
        }
        let userId = that.data.userinfo.id
        mode.report(JSON.stringify(arr), userId).then(
            item => {
                if (item.code == 1) {
                    that.setData({
                        reportId:item.data.report_id
                    })
                    if (that.data.userinfo.is_over_test == 1) {     //第一次答题
                        that.getUserInfo(userId)
                    }
                    that.toAddCart(item.data.goods_info_ids)
                    
                    setTimeout(() => {
                        that.setData({
                            showEnd:true
                        })
                    }, 1000);
                } else {
                    wx.showToast({
                        title: '生成报告失败',
                        icon: 'error'
                    })
                }

            })
    },
    goBeAll () {
        var that = this
        let item = that.data.list[that.data.nowId]
        if (that.data.sortList.length == 1) {
            that.data.submitList[that.data.nowId] = {
                chose: that.data.sortList[0].answer_id,
                id: item.id
            }
            item.hideShow = true
            that.data.taikList.push(item)
            that.setData({
                submitList: that.data.submitList,
                taikList: that.data.taikList
            })
            that.nextStep()
        } else if (that.data.sortList.length > 1) {
            item.chose = that.data.sortList
            item.allSort = 1
            that.data.taikList.push(item)
            setTimeout(() => {
                that.setData({
                    taikList: that.data.taikList
                })           
            }, 1500);
            
        } else {
            that.data.submitList[that.data.nowId] = {
                chose: '',
                id: item.id
            }
            item.hideShow = true
            that.data.taikList.push(item)
            setTimeout(() => {
                that.setData({
                    submitList: that.data.submitList,
                    taikList: that.data.taikList
                })
                that.nextStep()            
            }, 1500);
        }
        setTimeout(function () {
            that.pageScrollToBottom()
        }, 1800)
    },
    // 获取容器高度，使页面滚动到容器底部
    pageScrollToBottom: function () {
        wx.createSelectorQuery().select('.bigBox').boundingClientRect(function (rect) {
            // 使页面滚动到底部
            wx.pageScrollTo({
                scrollTop: rect.height
            })
        }).exec()
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        that = this
        this.setData({
            list: [], //所有的问题
            nowId: 0,       //当前答题进度
            juli: "0",      //进度距离
            submitList: [],  //提交答案列表
            shunxu: 1, //排序
            twoMultiple: [],
            nowimg: '',   //现在选中的图片
            taikList: [],   //对话列表
            openAnswer: '',
        })
        //设置用户信息
        var uinfo = wx.getStorageSync('uinfo')
        if (uinfo && uinfo.user) {
            that.setData({
                userinfo: uinfo.user
            })
            that.getUserInfo(uinfo.user.id)
        }else{
            wx.setStorage({
                data: '/pages/questionnaire/questionnaire',
                key: 'lastUrl',
            })
            wx.redirectTo({
              url: '/pages/register/register',
            })
        }

        this.getdata() //获取题目列表
    },

    getUserInfo (userid) {
        let that = this
        var userInfo = wx.getStorageSync('uinfo')
        mode.getUserInfo(userid).then(item => {
            userInfo.user = item.data
            wx.setStorage({ key: 'uinfo', data: userInfo })
            that.setData({
                userinfo: item.data,
                userid: item.id
            })
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
})